package com.gzittc.gzgm.gm.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.gzittc.gzgm.R;
import com.gzittc.gzgm.common.base.BaseActivity;
import com.gzittc.gzgm.common.util.Utils;
import com.gzittc.gzgm.gm.model.db.DBHelper.AndroidCaseManger;
import com.gzittc.gzgm.gm.model.db.bean.Case.Choice;
import com.gzittc.gzgm.gm.model.db.bean.PSExam;
import com.gzittc.gzgm.gm.ui.adapter.ExamTopicAdapter;
import com.gzittc.gzgm.gm.ui.fragment.ExamTopicFragment;

import org.litepal.crud.DataSupport;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/22.
 */

public class ExamStartActivity extends BaseActivity implements BaseActivity.OnDialogClickListener{

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.push_test_paper)
    Button pushTestPaper;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tab_labelling)
    TabLayout tabLabelling;
    @BindView(R.id.vp_test_paper)
    ViewPager vpTestPaper;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    private int TYPE;
    private ArrayList<Choice> listChoice;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_exam_start;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        imgBack.setVisibility(View.GONE);
        pushTestPaper.setVisibility(View.VISIBLE);
        setPageTitle("考试中…");
        //根据那种考试，时间，题目数量，初始化
        initDatabase();
        initViewPager();//初始化viewpager
        initTabLayout();//初始化tablayout

    }

    private void initDatabase() {
        Intent intent = getIntent();
        switch(intent.getStringExtra("sql")){
            case "17ps_exam":
                TYPE=0;
                size = DataSupport.findAll(PSExam.class).size();//总题数
                allTime = intent.getIntExtra("time",0) * 60;//总时间
                List<PSExam> temp =DataSupport.select("answer").find(PSExam.class);
                rightAnswer = new String[temp.size()];
                for(int i=0;i<temp.size();i++){
                    rightAnswer[i] = temp.get(i).getAnswer();
                }
                break;
            case "AndroidCase":
                AndroidCaseManger manger = new AndroidCaseManger(this);
                SQLiteDatabase db = manger.DBManager();
                listChoice = manger.queryChioceAll(db);
                TYPE=1;
                size = listChoice.size();
                allTime = intent.getIntExtra("time",0) * 60;
                rightAnswer = new String[listChoice.size()];
                for(int i = 0; i< listChoice.size(); i++){
                    rightAnswer[i] = listChoice.get(i).getAnswer();
                }
                break;
        }
    }

    int size = 0;

    String[] studentAnswer ;//考生回答的答案
    String[] rightAnswer ;//正确答案

    private void initTabLayout() {
        studentAnswer = new String[size];//初始化考生回答的数组
        time = allTime+0;//初始化时间
        tvLeft.setTextSize(15);
        tvLeft.setVisibility(View.VISIBLE);
        tvLeft.setText(nowtime + Utils.TimetoString(time));
        handler.postDelayed(runnable, 1000);
        tabLabelling.setupWithViewPager(vpTestPaper);
        for (int i = 0; i < size; i++)
            tabLabelling.getTabAt(i);
        tabLabelling.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    /**
     * 倒计时
     * @author YZC
     * created at 2018-01-07
     */
    int allTime = 0;
    int time = 0;
    String nowtime = "剩余：";

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            time -= 1;
            if (time != 0) {
                handler.postDelayed(this, 1000);
                tvLeft.setText(nowtime + Utils.TimetoString(time));
            } else {
                tvLeft.setVisibility(View.GONE);
                Intent intent = new Intent(ExamStartActivity.this, ExamFinishedActivity.class);
                startActivity(intent);
                finish();
            }
        }
    };

    private void initViewPager() {
        List<Fragment> list = new ArrayList<>();
        String[] tabs = new String[size];
        for(int i=0;i<size;i++){
            tabs[i] = "第"+(i+1)+"题";
            ExamTopicFragment fragment = new ExamTopicFragment();
            if(TYPE == 0){
                List<PSExam> mDestList = DataSupport.where("id = ?", ""+(i+1) ).find(PSExam.class);
                fragment.setContent(mDestList.get(0));
            }else if(TYPE == 1){
                fragment.setContent(TYPE,listChoice.get(i));
            }
            list.add(fragment);
        }
        vpTestPaper.setAdapter(new ExamTopicAdapter(getSupportFragmentManager(), list,tabs));
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v, int id) {

    }
    /**
     * fragment里选择了答案后，提交到activity中
     * @author YZC
     * created at 2018-01-07
     */
    public void setAnaswer(boolean[] anaswer,int id){
        String temp = "";
        for(int i=0;i<anaswer.length;i++){
            if(anaswer[i]==true){
                switch(i){
                    case 0:temp +="A"; break;
                    case 1:temp +="B";break;
                    case 2:temp +="C";break;
                    case 3:temp +="D";break;
                }
            }
        }
        studentAnswer[id-1]=temp;
    }

    /**
     * 交卷逻辑
     * @author YZC
     * created at 2018-01-07
     */
    @OnClick({R.id.push_test_paper})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.push_test_paper://交卷
                showDialog("",getResources().getString(R.string.push_prompt),this,"交卷","再检查一下");
                break;
        }
    }

    /**
     * dialog确认按钮
     * @param dialog
     */
    @Override
    public void onConfirm(DialogInterface dialog) {
        int count = checkAnswer();
        Intent intent = new Intent(this, ExamFinishedActivity.class);
        intent.putExtra("count",count+"");
        double chengji = ((double)count/size)*100;
        DecimalFormat df = new DecimalFormat("0.00");
        intent.putExtra("chengji",df.format(chengji)+"分");
        String thisTime = Utils.TimetoString(allTime-time);
        intent.putExtra("number",getIntent().getStringExtra("number"));
        intent.putExtra("time",thisTime);
        startActivity(intent);
        finish();
    }

    @Override
    public void onCancel(DialogInterface dialog) {

    }

    /**
     * 点击交卷后，检查答案
     * @author YZC
     * created at 2018-01-07
     */
    private int checkAnswer() {
        int count = 0;
        for(int i=0;i<size;i++){
            StringBuffer sb = new StringBuffer().append(rightAnswer[i]);
            if(studentAnswer[i]==null)
                continue;
            if(rightAnswer[i].equals(studentAnswer[i]) || sb.indexOf(studentAnswer[i]) ==0){
                count++;
            }
        }
        return count;
    }

    public void NextFragment(){
        int index = vpTestPaper.getCurrentItem();
        if(index<size){
            vpTestPaper.setCurrentItem(index+1);
        }
    }

    @Override
    public void onBackPressed() {
        //null
    }
}
